""" 

    Quiz.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This script checks to see if you've already taken the quiz or if you have a challenge pending.
    If you're eligible, then it chooses the answers you'll see for the quiz and displays the final page.
    
"""

__author__ = "Will Turnage (will@wubbahed.com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string
import random

from sets import Set
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.ext import db
from utils import fbUtil, dbUtil, UserDistrict, SunlightUtil, Challenges

class MainHandler(webapp.RequestHandler):
        
    def post(self):
    
        try:
            #check if Facebook app is installed
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, True, "quiz")
            if self.facebookapi is None:
                return
                   
            user = self.facebookapi.users.getInfo([self.facebookapi.uid], ['uid', 'name', 'current_location'])[0]
            userInfo = dbUtil().getLegislatorForUser(user["uid"], user["current_location"], True)
            
            if userInfo is None:           
                path = os.path.join(os.path.dirname(__file__), '../templates/quizmap.fbml')
                self.response.out.write(template.render(path, userInfo))
            else:  
                userInfo["section"] = "challenge" 
                if not userInfo.has_key("rep"):
                    path = os.path.join(os.path.dirname(__file__), '../templates/quizmap.fbml')
                    self.response.out.write(template.render(path, userInfo))
                else:
                    
                    details = {"rep":[], "jrsen":[], "srsen":[]} 
                    query = Challenges.all()
                    query.filter("challengee =", int(userInfo["uid"]))
                    query.filter("completed =", False)
                    result = query.fetch(1)
                    
                    if len(result) > 0:
                        
                        # user has a valid challenge in the database   
                    
                        MAX_WRONG_ANSWERS = 7
                        questions = {"rep":[], "jrsen":[], "srsen":[]}
                        if userInfo.has_key("state"):
                            if const.LEGISLATORS_BY_STATE.has_key(userInfo["state"]):
                                stateSize = len(const.LEGISLATORS_BY_STATE[userInfo["state"]]["representatives"])
                                if stateSize > MAX_WRONG_ANSWERS:
                                    while len(questions["rep"]) < MAX_WRONG_ANSWERS:
                                        randomLegislator = const.LEGISLATORS_BY_STATE[userInfo["state"]]["representatives"][random.randint(0,stateSize-1)]
                                        if randomLegislator != userInfo["rep"]:
                                            if not randomLegislator in questions["rep"]:
                                                questions["rep"].append(randomLegislator)
                                        
                        if len(questions["rep"]) < MAX_WRONG_ANSWERS:
                            while len(questions["rep"]) < MAX_WRONG_ANSWERS:
                                randomLegislator = const.REPRESENTATIVES[random.randint(0,len(const.REPRESENTATIVES)-1)]
                                if randomLegislator != userInfo["rep"]:
                                    if not randomLegislator in questions["rep"]:
                                        questions["rep"].append(randomLegislator)
    
                        questions["rep"].insert(random.randint(0,MAX_WRONG_ANSWERS), userInfo["rep"])
                        
                        if userInfo.has_key("jrsen"):           
                            if len(questions["jrsen"]) < MAX_WRONG_ANSWERS:
                                while len(questions["jrsen"]) < MAX_WRONG_ANSWERS:
                                    randomLegislator = const.SENATORS[random.randint(0,len(const.SENATORS)-1)]
                                    if (randomLegislator != userInfo["jrsen"]) and (randomLegislator != userInfo["srsen"]):
                                        if not randomLegislator in questions["jrsen"]:
                                            questions["jrsen"].append(randomLegislator)
                                        
                            questions["jrsen"].insert(random.randint(0,MAX_WRONG_ANSWERS), userInfo["jrsen"])
                        
                        if userInfo.has_key("srsen"):
                            if len(questions["srsen"]) < MAX_WRONG_ANSWERS:
                                while len(questions["srsen"]) < MAX_WRONG_ANSWERS:
                                    randomLegislator = const.SENATORS[random.randint(0,len(const.SENATORS)-1)]
                                    if (randomLegislator != userInfo["jrsen"]) and (randomLegislator != userInfo["srsen"]):
                                        if not randomLegislator in questions["jrsen"]:
                                            if not randomLegislator in questions["srsen"]:
                                                questions["srsen"].append(randomLegislator)
                                        
                            questions["srsen"].insert(random.randint(0,MAX_WRONG_ANSWERS), userInfo["srsen"])
                                     
                        for key in questions.keys():
                            for id in questions[key]:
                                details[key].append({"id": id, "name": const.FRIENDLY_NAME[id]}) 
                                    
                        path = os.path.join(os.path.dirname(__file__), '../templates/quiz.fbml')
                        self.response.out.write(template.render(path, details ))
                    else:
                        
                        # nothing in the db.  have they taken the quiz already?
                        query = Challenges.all()
                        query.filter("challengee =", int(userInfo["uid"]))
                        query.filter("completed =", True)
                        results = query.fetch(1)
                        if len(results) > 0:
                            for result in results:
                                friend_name = self.facebookapi.users.getInfo([result.challenger], ['uid', 'name'])
                                for friend in friend_name:
                                    details["challenger"] = friend["name"]
                                details["challengee_score"] = result.challengeescore
                                
                            path = os.path.join(os.path.dirname(__file__), '../templates/heading.fbml')
                            self.response.out.write(template.render(path, userInfo))
                            path = os.path.join(os.path.dirname(__file__), '../templates/quiztaken.fbml')
                            self.response.out.write(template.render(path, details ))
                        else:
                            # there are no challenges in the database
                            path = os.path.join(os.path.dirname(__file__), '../templates/heading.fbml')
                            self.response.out.write(template.render(path, userInfo))
                            path = os.path.join(os.path.dirname(__file__), '../templates/quiznochallenge.fbml')
                            self.response.out.write(template.render(path, details ))
                
                
        except urlfetch.DownloadError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Google AppEngine ain't working"}))
            
        except facebook.FacebookError, e:
            path = os.path.join(os.path.dirname(__file__), '../templates/error.fbml')
            self.response.out.write(template.render(path, {"error":"Sorry, Facebook ain't working - " + str(e.msg)})) 
            
            
        
        
            
  
def main():
	application = webapp.WSGIApplication([('/fb/quiz', MainHandler)],
									   debug=True)
	run_wsgi_app(application)

# load our custom filters		   
webapp.template.register_template_library('customfilters')

if __name__ == '__main__':
	main()
